package fr.sedoo.metadata.client.ui.widget.common;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.metadata.client.ui.label.RoleLabelProvider;
import fr.sedoo.metadata.shared.domain.dto.MetadataContactDTO;

public class RolePanel extends Composite {

	@UiField
	VerticalPanel mainPanel;

	private HashMap<String, CheckBox> checkBoxes = new HashMap<String, CheckBox>();

	private static SecondaryRolePanelUiBinder uiBinder = GWT.create(SecondaryRolePanelUiBinder.class);

	private List<String> roles;

	interface SecondaryRolePanelUiBinder extends UiBinder<Widget, RolePanel> {
	}

	public RolePanel(List<String> roles) {
		this.roles = roles;
		initWidget(uiBinder.createAndBindUi(this));

		Iterator<String> iterator = roles.iterator();
		while (iterator.hasNext()) {
			addWidgetFromRole(iterator.next());

		}
	}

	public void edit(String value) {
		reset();
		String aux = StringUtil.trimToEmpty(value);

		Iterator<String> iterator = roles.iterator();
		while (iterator.hasNext()) {
			String role = iterator.next();
			CheckBox checkBox = checkBoxes.get(role);
			checkBox.setValue(aux.contains(role));
		}
	}

	public String flush() {
		StringBuilder sb = new StringBuilder();

		Iterator<String> iterator = roles.iterator();
		while (iterator.hasNext()) {
			String role = iterator.next();
			CheckBox checkBox = checkBoxes.get(role);
			if (checkBox.getValue()) {
				sb.append(MetadataContactDTO.ROLE_SEPARATOR + role);
			}
		}

		String aux = sb.toString();
		if (StringUtil.isNotEmpty(aux)) {
			// On enlève le premier |
			return aux.substring(1);
		} else {
			// On retourne en fait une chaine vide
			return aux;
		}
	}

	private void reset() {
		// Pas de traitement particulier
	}

	private void addWidgetFromRole(String role) {
		HorizontalPanel panel = new HorizontalPanel();
		panel.setSpacing(5);
		panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		CheckBox checkBox = new CheckBox();
		checkBox.setWordWrap(false);
		checkBox.setText(RoleLabelProvider.getLabel(role));
		panel.add(checkBox);
		Label tooltip = new Label(" " + RoleLabelProvider.getTooltip(role));
		tooltip.setStyleName("instructions");
		panel.add(tooltip);
		checkBoxes.put(role, checkBox);
		mainPanel.add(panel);
	}

}
